package edu.whu.assignment8.impl;

import edu.whu.assignment8.dao.GoodsRepository;
import edu.whu.assignment8.entity.Goods;
import edu.whu.assignment8.exception.GoodsAdminException;
import edu.whu.assignment8.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsRepository goodsRepository;

    @Override
    public Goods addGoods(Goods goods) throws GoodsAdminException {
        if (goods.getId() != null) {
            if (goodsRepository.findById(goods.getId()).isPresent()) {
                throw new GoodsAdminException("添加商品失败：商品已经存在");
            }
        }
        return goodsRepository.save(goods);
    }

    @Override
    public Goods getGoods(long id) {
        return goodsRepository.findById(id).get();
    }


    @Override
    public Page<Goods> findGoods(@NotNull Map<String, Object> condition, @NotNull Pageable pageable) {
        return goodsRepository.findAll((root, query, cb) -> {
            List<Predicate> pList = new ArrayList<>();
            if (condition.containsKey("name")) {
                pList.add(cb.like(root.get("name"), "%" + condition.get("name") + "%"));
            }
            if (condition.containsKey("price")) {
                pList.add(cb.le(root.get("price"), (float) condition.get("price")));
            }
            if (condition.containsKey("stockQuantity")) {
                pList.add(cb.ge(root.get("stockQuantity"), (float) condition.get("stockQuantity")));
            }

            if (condition.containsKey("category")) {
                pList.add(cb.equal(root.get("category"), condition.get("category")));
            }
            if (condition.containsKey("goodsType")) {
                pList.add(cb.equal(root.get("goodsType"), condition.get("goodsType")));
            }
            if (condition.containsKey("supplierName")) {
                //根据供应商名称跨表查询，使用root.join('导航属性名').get('关联实体的属性')来表示
                pList.add(cb.equal(root.join("supplierList").get("name"), condition.get("supplierName")));
            }
            return cb.and(pList.toArray(new Predicate[pList.size()]));
        }, pageable);

    }

    @Override
    public void updateGoods(long id, Goods goods) throws GoodsAdminException {
        if (!goodsRepository.findById(id).isPresent()) {
            throw new GoodsAdminException("修改商品失败：商品不存在");
        }
        goodsRepository.saveAndFlush(goods);
    }

    @Override
    public void deleteGoods(long id) {
        goodsRepository.deleteById(id);
    }



}
